﻿using System;
using System.Collections.Generic;
using System.Text;
using Ineva.Data;
using System.Data.SQLite;

namespace Ineva.Service
{
   public  class ClientInfoSvr
    {

        static object Lock = new object();
        static object GetLock(string Metodo, string UsuarioPerfilBase)
        {
            string Hash = Metodo + "-" + UsuarioPerfilBase;
            if (!Locks.ContainsKey(Hash))
            {
                lock (Lock)
                {
                    if (!Locks.ContainsKey(Hash))
                    {
                        object o = new object();
                        Locks.Add(Hash, o);
                        return o;
                    }
                    else
                    {
                        return Locks[Hash];
                    }
                }
            }
            else
            {
                return Locks[Hash];
            }
        }
        static Dictionary<string, Object> Locks = new Dictionary<string, object>();
        public void InsertClientInfo(int idnews,string Email,string Ip, string MachineName, string Lang, string UrlRef, bool IsMovil, string OS, string Browser)
        {
            lock (GetLock("ClientInfo", idnews.ToString()))
            {
                SimpleClientInfo s = new SimpleClientInfo(idnews, Email, DateTime.Now, Ip, MachineName, Lang, UrlRef, IsMovil, OS, Browser);
                ClientInfo c = new ClientInfo(s);
                c.Insert();
            }
        }
        public void InsertVisitasPorDia(int idnews )
        {
            lock (GetLock("ClientInfo", idnews.ToString()))
            {
                VisitasPorDia v = new VisitasPorDia();
                DateTime  now = DateTime.Now;
                now = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
                v.LoadByFecha(idnews, now);
                if (v.Simple == null)
                {
                    v = new VisitasPorDia(new SimpleVisitasPorDia(idnews, now, 1));
                    v.Insert();
                }
                else
                {
                    v.Simple.Visitas++;
                    v.Update();
                }
            }
        }

    }
}
